package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

@Slf4j(topic = "c.TestForkJoin2")
public class TestForkJoin2 {
    public static void main(String[] args) {
        final ForkJoinPool pool = new ForkJoinPool(4);
//        System.out.println(pool.invoke(new MyTask(5)));
        System.out.println(pool.invoke(new AddTask3(1,5)));

        //
    }
}

@Slf4j(topic = "c.MyTask")
class AddTask3 extends RecursiveTask<Integer>{

    private int begin;
    private int end;

    public AddTask3(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (begin == end) {
            log.debug("join() {}",begin);
            return begin;
        }

        if(end - begin == 1){
            log.debug("join() {} + {} = {}",begin,end,end+begin);
            return end+begin;
        }

        int mid = (end+begin)/2;

        final AddTask3 t1 = new AddTask3(begin, mid);
        t1.fork();

        final AddTask3 t2 = new AddTask3(mid+1, end);
        t2.fork();
        log.debug("fork() {} + {} = ?", t1, t2);

        int result = t1.join() + t2.join();
        log.debug("join() {} + {} = {}",t1,t2,result);
        return result;
    }
}


//1-n 之间整数的和
@Slf4j(topic = "c.MyTask")
class MyTask extends RecursiveTask<Integer>{

    private int n;

    public MyTask(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return "{" +
                "n=" + n +
                '}';
    }

    @Override
    protected Integer compute() {
        if (n == 1){
            log.debug("join() {}",n);
            return 1;
        }
        final MyTask t1 = new MyTask(n - 1);
        t1.fork();//让一个线程去执行此任务
        log.debug("fork() {} + {}",n,t1);

        final int result = t1.join() + n;//获取任务结果
        log.debug("join() {} + {} = {}",n,t1,result);

        return result;
    }
}
